<?php 
class directoriesAction extends sfAction{
	private $finder;
	private $max_depth = 0;
	public function execute($request){
		//checking authentication
		$directory_path  	= $request->getParameter('directory_path','');
		$this->max_depth	= $request->getParameter('max_depth', 0);
		$jsonReturn = array();
			
		//if(!empty($directory_path)){
			if($directory_path=='all') $directory_path = '';
			$this->finder = new sfFinder();
			$this->finder->maxdepth(0);
			$this->finder->setType('directory');
			$direcList = $this->finder->in(sfConfig::get('sf_upload_dir').'/'.$directory_path);
			$jsonReturn[0] = array(
				'has_sub' => count($direcList),
				'path'	  => $directory_path==''?'all':$directory_path,
				'name'	  => basename($directory_path)==''?'app':basename($directory_path),
				'children'=> $this->getSub($directory_path)
			);
		//} 
		print_r(json_encode($jsonReturn));
		return sfView::NONE;
	}
	private function getSub($path, $depth = 2){
		if($depth>$this->max_depth && $this->max_depth>0) return array();
		$direc_list = $this->finder->in(sfConfig::get('sf_upload_dir').'/'.$path);
		$rt = array();
		foreach($direc_list as $dir){
			$arr = explode(sfConfig::get('app_uploadControl_path'), $dir);
			if(count($arr)<2) continue;
			$rt[] = array(
					'has_sub' => $this->hasSubFolder($arr[1]),
					'path'	  => $arr[1],
					'name'	  => basename($arr[1]),
					'children'=> $this->getSub($arr[1], $depth+1)
				);
		}
		return $rt;
	}
	private function hasSubFolder($path){
		return count($this->finder->in(sfConfig::get('sf_upload_dir').'/'.$path));
	}
}